package com.gitlab.lucky.common.weixin;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.gitlab.lucky.common.enums.Constant;
import com.gitlab.lucky.common.redis.RedisService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

/**
 * @program: lucky
 * @author: Mr.Han
 * @create: 2018-11-05 14:42
 **/
@Component
public class WeixinUtil {
    public static final Logger LOGGER = LoggerFactory.getLogger(WeixinUtil.class);
    @Autowired
    private RedisService redisService;

    /**
     * 从微信获取AccessToken
     *
     * @return
     */
    public String getAccessToken(Integer platform) {
        String accessToken = (String) redisService.get(Constant.WX_ACCESS_TOKEN_KEY + platform);
        if (StringUtils.isBlank(accessToken)) {
            LOGGER.info("获取accessToken失败");
        }
        return accessToken;
    }

    /**
     * 上传至微信媒体服务器
     *
     * @param file
     * @param platform
     * @return
     */
    public JSONObject uploadMedia(File file, Integer platform) {
        String BoundaryStr = "------------7da2e536604c8";
        String body = HttpUtil.createPost(String.format(Constant.WX_UPLOAD_MEDIA_URL, getAccessToken(platform)))
                .header("Connection", "keep-alive")
                .header("Accept", "*/*")
                .header("Content-Type", "multipart/form-data;boundary=" + BoundaryStr)
                .form("media", file, ContentType.APPLICATION_OCTET_STREAM, file.getName())
                .execute()
                .body();
        file.delete();
        return JSONObject.parseObject(body);
    }

    /**
     * 防止重复请求
     */
    public boolean isSubmit(Integer platform, String openId) {
        //防止重复请求
        Object o = redisService.get(Constant.SUBMIT_KEY + platform + openId);
        if (o != null) {
            return true;
        }
        redisService.set(Constant.SUBMIT_KEY + platform + openId, platform + openId, Constant.SUBMIT_TIME);
        return false;
    }

    /**
     * 删除防并发缓存
     */
    public void delSubmitCache(String key) {
        redisService.del(key);
    }
    public static String getSign(Map map,String PAY_JS_KEY) {
        StringBuffer sb = new StringBuffer();
        Set<String> strings = map.keySet();
        for (String object : strings) {
            Object val = map.get(object);
            sb.append(object);
            sb.append("=");
            sb.append(val);
            sb.append("&");
        }
        sb.append("key=");
        sb.append(PAY_JS_KEY);
        String s = DigestUtils.md5Hex(sb.toString());
        return s.toUpperCase();
    }
}
